package cn.liujianbo.easycode.common;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 字典的整数值序列化为数字
 *
 * @author 刘建波
 * @date 2022-05-25 21:16
 */
public class DictStringNumberSerializer extends JsonSerializer<String> {

    private static final Pattern NUMBER_PATTERN = Pattern.compile("(^[0-9]{1}$)|(^[1-9]{1}[0-9]*$)");

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (NUMBER_PATTERN.matcher(s).matches()) {
            jsonGenerator.writeNumber(s);
        } else {
            jsonGenerator.writeString(s);
        }
    }
}
